#!/bin/sh

. /etc/rc.freenas

service=/usr/sbin/service
status_file="/var/run/directoryservice.nis"

nisctl_cache_fill()
{
	LD_LIBRARY_PATH=/usr/local/lib /usr/local/www/freenasUI/tools/cachetool.py fill &
}

nisctl_cache_expire()
{
	LD_LIBRARY_PATH=/usr/local/lib /usr/local/www/freenasUI/tools/cachetool.py expire &
}

nisctl_cmd()
{
	local args="$*"

	if [ -n "${args}" ]
	then
		logger -t NIS "${args}"
		${args}
		return $?	
	fi		

	return 0
}

nisctl_start()
{
	nis_set 1

	nisctl_cmd ${service} ix-passwd start
        nisctl_cmd ${service} ix-hostname start

	if ! nisctl_cmd ${service} ix-nsswitch start
	then
		nisctl_cmd ${service} ix-passwd start
        	nisctl_cmd ${service} ix-hostname start
		nis_set 0
		return 1
	fi

	if ! nisctl_cmd ${service} nisdomain start
	then
		nisctl_cmd ${service} ix-passwd start
        	nisctl_cmd ${service} ix-hostname start
		nis_set 0
		return 1
	fi

	if ! nisctl_cmd ${service} ypbind start
	then
		nisctl_cmd ${service} ix-passwd start
        	nisctl_cmd ${service} ix-hostname start
		nis_set 0
		return 1
	fi

	nisctl_cache_fill
	touch "${status_file}"
	return 0
}

nisctl_stop()
{
	nisctl_cache_expire

	nisctl_cmd ${service} ypbind stop
	nisctl_cmd ${service} nisdomain stop
	nisctl_cmd ${service} ix-nsswitch stop
	nisctl_cmd ${service} ix-hostname start
	nisctl_cmd ${service} ix-passwd start

	nis_set 0
	. /etc/rc.conf.local

	rm -f "${status_file}"
}

nisctl_status()
{
	nisctl_cmd ypwhich
}

name="nisctl"
start_cmd='nisctl_start'
status_cmd='nisctl_status'
stop_cmd='nisctl_stop'
extra_commands='status'

load_rc_config $name
run_rc_command "$1"
